<?php
// +----------------------------------------------------------------------
// | Class  模型基类
// +----------------------------------------------------------------------
// | Copyright (c) 2020
// +----------------------------------------------------------------------

class Model{

    /**
     * Notes: 数据库配置
     * User: ZhuHaili
     * Date: 2022/10/11
     */
    private static function dbConfig(){
        // 包含数据库配置文件
        $databaseFile = SYS_PATH.'config/database.php';
        $db_Con  = array();
        if(is_file($databaseFile)){
            $db_Con = require $databaseFile;
        }
        if(empty($db_Con)){

            $errStr ='Database no link type exists:';
            sys_err_loger($errStr, 'config/database.php / core/Model.class.php', __LINE__);
        }
        return $db_Con;
    }

    /**
     * Notes: 判断数据库参数是否正确
     * User: ZhuHaili
     * Date: 2022/3/17
     */
    private static function dbSignParam($dbKey){
        $dbConfig = self::dbConfig();
        // 判断指定的数据库
        if(!isset($dbConfig[$dbKey])){

            $errStr ='Database no link type exists:'.$dbKey;
            sys_err_loger($errStr, 'config/database.php / core/Model.class.php', __LINE__);
        }
        $dbParam = $dbConfig[$dbKey];
        if(!isset($dbParam['db_name'])){

            $errStr = 'Database parameter error:`db_name` can not be empty';
            sys_err_loger($errStr, 'config/database.php / core/Model.class.php', __LINE__);
        }
        $mustParam = array(
            'db_type' => 'mysql', 'db_link' => 'mysqli', 'db_name' => 'zhlcms2.3', 'db_host'=>'localhost', 'db_port' => 3306,
            'db_user' => 'root', 'db_pwd' => '', 'db_fix' => '', 'db_char' => 'utf8');
        foreach($mustParam as $k=>$v){
            if(!isset($dbParam[$k])){
                $dbParam[$k] = $v;
            }
        }
        return $dbParam;
    }

    /**
     * Notes:连接指定数据库
     * User: ZhuHaili
     */
    public static function conn($dbKey){
        $dbKeyParam = self::dbSignParam($dbKey);    // 验证指定的数据库配置参数合法性
        $dbType = $dbKeyParam['db_type'];           // 数据库类型
        $dbLink = $dbKeyParam['db_link'];           // 链接类型
        if($dbType == 'mysql'){
            if($dbLink == 'mysqli'){
                $db = DbMySqli::getInstance($dbKeyParam);
                $db->db_config = $dbKeyParam;
                return $db;
            }else if($dbLink == 'pdo'){
                $db = DbMysqlPDO::getInstance($dbKeyParam);
                $db->db_config = $dbKeyParam;
                return $db->db;
            }
        }else if($dbType == 'oracle'){
            $db = DbOraclePDO::getInstance($dbKeyParam);
            $db->db_config = $dbKeyParam;
            return $db->db;
        }

        $errStr = 'Database parameter error:`db_name` can not be empty';
        sys_err_loger($errStr, 'config/database.php / core/Model.class.php', __LINE__);
    }

    /**
     * 析构方法
     */
    /*function __destruct() {
		
    }*/
}